package com.lcy.smartcity.controller;

import com.lcy.smartcity.dto.UserDTO;
import com.lcy.smartcity.dto.UserLoginDTO;
import com.lcy.smartcity.dto.UserRegisterDTO;
import com.lcy.smartcity.entity.User;
import com.lcy.smartcity.service.UserService;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/users")
@CrossOrigin(origins = "http://localhost:5173")
public class UserController {

    @Autowired
    private UserService userService;

    // 注册
    @PostMapping("/register")
    public ResponseEntity<?> register(@RequestBody UserRegisterDTO registerDTO, HttpSession session) {
        // 检查参数
        if (registerDTO.getUsername() == null || registerDTO.getUsername().isEmpty() ||
            registerDTO.getPassword() == null || registerDTO.getPassword().isEmpty() ||
            registerDTO.getPhoneNumber() == null || registerDTO.getPhoneNumber().isEmpty()) {
            return ResponseEntity.badRequest().body("用户名、密码和邮箱不能为空");
        }

        boolean success = userService.register(
                registerDTO.getUsername(),
                registerDTO.getPassword(),
                registerDTO.getPhoneNumber()
        );
        if (success) {
            return ResponseEntity.ok("注册成功");
        } else {
            return ResponseEntity.badRequest().body("用户名或手机号已存在");
        }
    }

    // 登录
    @PostMapping("/login")
    public ResponseEntity<?> login(@RequestBody UserLoginDTO loginDTO, HttpSession session) {
        if (loginDTO.getPhoneNumber() == null || loginDTO.getPhoneNumber().isEmpty() ||
            loginDTO.getPassword() == null || loginDTO.getPassword().isEmpty()) {
            return ResponseEntity.badRequest().body("用户名和密码不能为空");
        }

        User user = userService.login(loginDTO.getPhoneNumber(), loginDTO.getPassword());
            if (user != null) {
                // 登录成功，将用户信息存入Session
                session.setAttribute("user", user);

                UserDTO userDTO = new UserDTO();
                BeanUtils.copyProperties(user, userDTO);
                return ResponseEntity.ok(userDTO);
            } else {
                return ResponseEntity.badRequest().body("用户名或密码错误");
            }
    }

    // 登出
    @PostMapping("/logout")
    public ResponseEntity<?> logout(HttpSession session) {
        session.invalidate();
        return ResponseEntity.ok("退出登录成功");
    }

    // 获取当前用户信息
    @GetMapping("/current")
    public ResponseEntity<?> getCurrentUser(HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return ResponseEntity.badRequest().body("未登录");
        }
        UserDTO userDTO = new UserDTO();
        BeanUtils.copyProperties(user, userDTO);
        return ResponseEntity.ok(userDTO);
    }

    // 获取当前所有用户信息
    @GetMapping("/all")
    public ResponseEntity<?> getAllUsers(HttpSession session) {
        User currentUser = (User) session.getAttribute("user");
        if (currentUser == null) {
            return ResponseEntity.badRequest().body("未登录");
        }

        // 只有管理员可以查看所有用户
        if (!currentUser.getIsAdmin()) {
            return ResponseEntity.badRequest().body("权限不足");
        }

        List<User> users = userService.getAllUsers();
        List<UserDTO> userDTOs = users.stream().map(u -> {
            UserDTO userDTO = new UserDTO();
            BeanUtils.copyProperties(u, userDTO);
            return userDTO;
        }).toList();

        return ResponseEntity.ok(userDTOs);
    }

    // 更新管理员权限
    @PutMapping("/{userId}/admin")
    public ResponseEntity<?> updateAdminStatus(
            @PathVariable Long userId,
            @RequestParam Boolean isAdmin,
            HttpSession session) {
        User currentUser = (User) session.getAttribute("user");
        if (currentUser == null) {
            return ResponseEntity.badRequest().body("未登录");
        }

        boolean success = userService.updateAdminStatus(userId, isAdmin, currentUser.getId());
        if (success) {
            return ResponseEntity.ok("用户权限更新成功");
        } else {
            return ResponseEntity.badRequest().body("权限更新失败");
        }
    }

    // 更改密码
    @PutMapping("/password")
    public ResponseEntity<?> updatePassword(
            @RequestParam String phoneNumber,
            @RequestParam String oldPassword,
            @RequestParam String newPassword,
            HttpSession session) {
        User currentUser = (User) session.getAttribute("user");
        if (currentUser == null) {
            return ResponseEntity.badRequest().body("未登录");
        }
        // 验证是否是当前用户修改自己的密码
        if (!currentUser.getPhoneNumber().equals(phoneNumber)) {
            return ResponseEntity.badRequest().body("只能修改自己的密码");
        }

        // 调用服务层更新密码
        boolean success = userService.updatePassword(phoneNumber, oldPassword, newPassword);
        if (success) {
            return ResponseEntity.ok("密码更新成功");
        } else {
            return ResponseEntity.badRequest().body("旧密码不正确");
        }
    }

}
